import React, { Component } from "react";
import {
  StyleSheet,
  Dimensions,
  View,
  WebView,
  Platform,
  NativeModules,
} from "react-native";

import { RNReload } from "components/Reload";
import config from "config";

const { iOSModule } = NativeModules; // 原生 iOS 模组

// 获取设备的宽度和高度
const { height: deviceHeight } = Dimensions.get("window");

const BaseScript = `
(function () {
          var height = null;
          function changeHeight() 
          {
            
              height = document.body.scrollHeight;
              height2 = document.documentElement.scrollHeight;
              height3 = document.body.clientHeight;
              if (window.postMessage) 
              {
                window.postMessage(JSON.stringify({
                  type: 'setHeight',
                  height: height,
                  height2: height2,
                  height3: height3,
                }))
              }
          }

    
          document.addEventListener('message', function(msg) 
          {
            setTimeout(changeHeight);

            var aNodes = document.getElementsByTagName('a');
            window.postMessage(JSON.stringify({
              type: 'jsToMsg',
              url: aNodes.length,
            }))
            for (var i = 0; i < aNodes.length; i++)
            {
              
              var url =aNodes[i].href;
              var text =aNodes[i].innerHTML;
              aNodes[i].href='javascript:void(0);';
              aNodes[i].url=url;
              aNodes[i].text=text;
              aNodes[i].onclick = function ()
              {
                var url2 =this.url;
                var text2 =this.text;
                window.postMessage(JSON.stringify({
                  type: 'jsToMsg',
                  text: text2,
                }))
                if (window.postMessage) 
                {
                  window.postMessage(JSON.stringify({
                    type: 'jsToWebView',
                    url: url2,
                    title: text2,
                  }))
                }
              }
            }
                   
        
          });
} ())
`;

export default class Index extends Component {
  state = {
    webViewHeight: deviceHeight - 200,
  };

  onMessage = event => {
    try {
      const action = JSON.parse(event.nativeEvent.data);
      if (action.type === "setHeight") {
        if (
          action.height >= action.height2 &&
          action.height >= action.height3
        ) {
          this.setState({
            webViewHeight: action.height !== 0 && action.height,
          });
        } else if (
          action.height2 >= action.height &&
          action.height2 >= action.height3
        ) {
          this.setState({
            webViewHeight: action.height2 !== 0 && action.height2,
          });
        } else if (
          action.height3 >= action.height &&
          action.height3 >= action.height2
        ) {
          this.setState({
            webViewHeight: action.height3 !== 0 && action.height3,
          });
        }
      } else if (action.type === "jsToWebView") {
        this.localUpdateVersion(action);
      } else if (action.type === "jsToMsg") {
        // console.log(action);
      }
    } catch (error) {
      // Toast.info(error);
      // console.log(error);
    }
  };

  // onNavigationStateChange = event => {
  //   // console.log(event); // 打印出event中属性
  // };

  localUpdateVersion = item => {
    console.log("跳转", item);
    // if (
    //   Platform.OS === "android" &&
    //   typeof RNReload.openBrowser === "function"
    // ) {
    //   RNReload.openBrowser(url);
    // } else if (Platform.OS === "ios") {
    //   Linking.openURL(url);
    // }
    let name = item.title;
    const reg = new RegExp(/(http|https):\/\/([\w.]+\/?)\S*/);
    if (reg.test(item.title)) {
      name = "";
    }
    if (Platform.OS === "android") {
      RNReload.toWebViewActivity(
        item.url,
        config.initUrl,
        name,
        global.lang.main.close
      );
    } else {
      iOSModule.toWebView(item.url, name, global.lang.main.close);
      // iOSModule.toCameraVC()
    }
  };

  // 渲染
  render() {
    const { content = "" } = this.props;
    const { webViewHeight } = this.state;
    const reg = new RegExp("<img", "g");
    const showText = content.replace(reg, '<img width="100%"');
    return (
      <View style={styles.container}>
        <WebView
          ref={ref => {
            this.webView = ref;
          }}
          automaticallyAdjustContentInsets
          startInLoadingState
          scrollEnabled={false}
          scalesPageToFit
          originWhitelist={["*"]}
          style={[styles.webView, { height: webViewHeight }]}
          onError={error => {
            console.log(error);
          }} // 加载失败的回调
          onLoad={() => {
            this.webView.postMessage("loaded");
          }} // 加载完成的回调
          onMessage={this.onMessage}
          mixedContentMode="always"
          onNavigationStateChange={this.onNavigationStateChange} // 当导航状态发生改变的回调
          // <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
          injectedJavaScript={`
                ${BaseScript}
              `}
          source={{
            html: `
            <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
            <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-CN" dir="ltr">
            <head>
            <meta charset="UTF-8"/>
            <meta name="viewport" content="width=device-width,initial-scale=1.0">
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
            <meta name="keywords" content="webview Android" />
            </head>
            <body><div>${showText}</div>
            </body></html>`,
            baseUrl: "",
          }}
        />
      </View>
    );
  }
}
// 样式定义
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
  },
});
